from flask import Flask, request, jsonify
import pandas as pd
import joblib
import os
from datetime import datetime

app = Flask(__name__)

# 加载模型
model_path = 'models/insurance_model.pkl'
if os.path.exists(model_path):
    model = joblib.load(model_path)
    print(f"模型已加载: {model_path}")
else:
    print(f"模型文件不存在: {model_path}")
    model = None


@app.route('/')
def index():
    """API主页"""
    return jsonify({
        'status': 'success',
        'message': '保险销售预测API已启动',
        'endpoints': [
            '/predict - 接受JSON格式数据并返回预测结果',
            '/health - 检查API健康状态'
        ]
    })


@app.route('/health')
def health_check():
    """健康检查接口"""
    status = 'healthy' if model is not None else 'unhealthy'
    return jsonify({
        'status': status,
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })


@app.route('/predict', methods=['POST'])
def predict():
    """预测接口"""
    try:
        # 检查模型是否已加载
        if model is None:
            return jsonify({
                'status': 'error',
                'message': '模型未加载'
            }), 500

        # 获取请求数据
        data = request.json

        # 检查数据格式
        if not data:
            return jsonify({
                'status': 'error',
                'message': '请求数据为空'
            }), 400

        # 将数据转换为DataFrame
        input_df = pd.DataFrame(data)

        # 确保所有需要的特征都存在
        required_features = [
            'Gender', 'Age', 'Driving_License', 'Previously_Insured',
            'Vehicle_Age', 'Vehicle_Damage', 'Annual_Premium',
            'Vintage', 'Region_Code_freq', 'Policy_Sales_Channel_freq'
        ]

        for feature in required_features:
            if feature not in input_df.columns:
                return jsonify({
                    'status': 'error',
                    'message': f'缺少必要特征: {feature}'
                }), 400

        # 进行预测
        predictions = model.predict_proba(input_df)[:, 1]

        # 构建响应
        response = {
            'status': 'success',
            'predictions': predictions.tolist(),
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }

        return jsonify(response)

    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500


if __name__ == '__main__':
    # 启动API服务
    print("启动保险销售预测API服务...")
    app.run(host='0.0.0.0', port=5000, debug=False)